import sqlite3
import copy, os
from SqliteHandler import SqliteHandler
from SqlDict import SqlDict




class Table4rate:

    
    rate_example = {
                    '光缆运杂费':0, '光缆运保费':0, '光缆采购及保管费':0,
                    '电缆运杂费':0, '电缆运保费':0, '电缆采购及保管费':0,
                    '塑料运杂费':0, '塑料运保费':0, '塑料采购及保管费':0,
                    '木材运杂费':0, '木材运保费':0, '木材采购及保管费':0,
                    '水泥运杂费':0, '水泥运保费':0, '水泥采购及保管费':0,
                    '其他运杂费':0, '其他运保费':0, '其他采购及保管费':0,
                    '设备运杂费':0, '设备运保费':0, '设备采购及保管费':0,
                    '设备(不安装)运杂费':0, '设备(不安装)运保费':0, '设备(不安装)采购及保管费':0,
                    }

    default_mat_dis = {'光缆': 0, '电缆': 0, '塑料': 0, '木材': 0, '水泥': 0, '其他': 0, '设备': 0, '设备(不安装)': 0}
    
    def __init__(self, prototype='book1', *args, **kwargs):

        # prototype 参数 book1 电源设备 book2 有线设备 book3 无线设备 book4 线路工程 book5 管道工程
        # **kwargs 中参数 mat_dis 为材料运距 dict() 
        # path 为db绝对路径
        self.rate = copy.deepcopy(self.rate_example)
        self.path = kwargs.get('path', 0)
        self.conn = SqliteHandler(self.path)
        prototype = prototype
        mat_dis = kwargs.get('mat_dis', self.default_mat_dis)


        data = self.get_type1_rate(mat_dis)
        for i in data:
            self.filldictitem(self.rate, i, data[i])

        data = self.get_type2_rate(prototype)
        for i in data:
            self.filldictitem(self.rate, i, data[i])

        self.conn.close()

    def getrate(self):
        return self.rate

    def customrate(self, *args, **kwargs):
        
        rate = self.getrate()
        for i in kwargs:
            self.filldictitem(rate, i, kwargs[i])
        
        return rate



    def get_type1_rate(self, mat_dis):
        # 获取 表四 分册无关距离有关 相关费率：
        # 运杂费

        dislist = list(mat_dis.values())
        dicttool = SqlDict()
        tablenamelist = [dicttool.geth2edict().get(i + '运杂费') for i in mat_dis]
        cn_tablenamelist = [i + '运杂费' for i in mat_dis]
        returndict = dict()
        for index, name in enumerate(tablenamelist):
            if name is None:
                name = 'equipment_transfees'
            data = self.conn.select(name)
            data = self.cursor2list(data)
            for i in data:
                if ((i[2] > 0) and  (i[2] >= dislist[index]) and (i[1] < dislist[index])) or dislist[index] == 0:
                    returndict[cn_tablenamelist[index]] =  (i[3])
                    break
                elif i == data[-1] and i[2] < 0:
                    rate = data[len(data) - 2][3] + i[3] * ((dislist[index] - data[len(data) - 1][1] ) // -i[2] + 1)
                    returndict[cn_tablenamelist[index]] =  rate
                    break
                elif i == data[-1] and i[2] > 0:
                    returndict[cn_tablenamelist[index]] =  (i[3])
        
        
        return returndict

    def get_type2_rate(self, prototype):
        # 获取 表四 分册有关定值 相关费率：
        # 运输保险费 采购及保管费

        tablelist = list(self.default_mat_dis)
        tablelist = [i + '运保费' for i in tablelist]
        dicttool = SqlDict()
        tablenamelist = [dicttool.geth2edict().get(i + '运输保险费') for i in tablelist]
        for index, i in enumerate(tablenamelist):
            if i is None:
                tablenamelist[index] = 'trans_insur'


        returndict = dict()
        for index, fee in enumerate(tablenamelist):
            data = self.conn.select(fee)
            data = self.cursor2list(data)
            for i in data:
                if i[1] == prototype:
                    returndict[tablelist[index]] = i[2]
                    break

        tablelist = list(self.default_mat_dis)
        tablelist = [i + '采购及保管费' for i in tablelist]
        dicttool = SqlDict()
        tablenamelist = [dicttool.geth2edict().get(i) for i in tablelist]
        for index, i in enumerate(tablenamelist):
            if i is None:
                tablenamelist[index] = 'storfees'

        tablenamelist[-1] = 'equipment_storfees'
        lentablenamelist = len(tablenamelist)

        for index, fee in enumerate(tablenamelist):
            data = self.conn.select(fee)
            data = self.cursor2list(data)
            for i in data:
                if i[1] == prototype:
                    if index == lentablenamelist - 1:
                        returndict[tablelist[index]] = i[3]
                    else:
                        returndict[tablelist[index]] = i[2]
                    break
        
        return returndict

    def cursor2list(self, cursor):
        # 将cursor可迭代对象转换为list
        mylist = []
        for i in cursor:
            temp = []
            for j in i:
                temp.append(j)
            mylist.append(temp)

        return mylist

    def filldictitem(self, d, key, item):
        # 将item写入复杂字典对应的key,key不能有重复
        for i in d:
            if not isinstance(d[i], dict):
                if i == key:
                    d[i] = item
                    return
            else:
                self.filldictitem(d[i], key, item)

if __name__ == "__main__":
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(BASE_DIR, 'db/rate.db')
    test = Table4rate('book4', path=path)
    data = test.getrate()
    print(data)